package mysql

import (
	"fmt"
	_ "github.com/go-sql-driver/mysql"
	"github.com/jinzhu/gorm"
	_ "github.com/jinzhu/gorm/dialects/mysql"
	"log"
)

//MysqlOpt  Connect options
type MysqlOpt struct {
	Host   string `yaml:"host"`
	Port   int    `yaml:"port"`
	User   string `yaml:"user"`
	DBName string `yaml:"dbname"`
	Passwd string `yaml:"passwd"`
}

//ConnectURL return conect url addr
//TODO enable sslmode=disable
func getConnectURL(opt *MysqlOpt) string {
	return fmt.Sprintf("%s:%s@tcp(%s:%d)/%s?charset=utf8", // "user:password@/dbname?charset=utf8&parseTime=True&loc=Local"
		opt.User,
		opt.Passwd,
		opt.Host,
		opt.Port,
		opt.DBName,
	)
}

//OpenMysql connect to Mysql database or exit
func OpenMysql(opt *MysqlOpt) *gorm.DB {
	client, err := gorm.Open("mysql", getConnectURL(opt))
	if err != nil {
		log.Fatalf("OpenMysql gorm.Open err: %s!\n", err.Error())
	}
	return client
}
